"""
Author: Meng
Date: 2018/6/2
"""
from flask import make_response
from flask_restful import Resource, reqparse
from app.api import api
from app.models.admin.config import FConfig, config_parse
from f_lib.principal.auth import admin_authority, auth_token
from f_lib.marshal_list import marshal
from f_lib.code import Msg
from f_lib.tool.mssr import MSsr
from datetime import datetime
from settings import SERVER_NAME, UPLOAD_PATH
import os
from f_lib.sync_tasks import all_tasks
from f_lib.sync_tasks.clear_download_zip import clear_zips
from concurrent.futures import ThreadPoolExecutor
from app.models.task.task import SysTasks
from app.models.admin.config import Notice

executor = ThreadPoolExecutor(max_workers=1)

base = dict(
    server_name=None,
    is_register=None,
    default_reg_role=None,
    backup_ip=None,
    backup_port=None,
    backup_base_path=None,
    share_expired=None,
    share_host=None,
    avatar_size=None,
    host=None,
)


class CrudConfig(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('server_name', type=str, required=True)

    @auth_token()
    @admin_authority
    def post(self):
        arg = config_parse.parse_args()
        config = FConfig.query_one(server_name=arg['server_name'])
        if config:
            arg['update_time'] = datetime.now()
            config.update(**arg)
            arg['update_time'] = str(config.update_time)
            arg['create_time'] = str(config.create_time)
            return Msg.success('ok', config=arg)
        else:
            FConfig.create(**arg)
            return Msg.success('ok', config=arg)

    @auth_token()
    @admin_authority
    def get(self):
        arg = self.parse.parse_args()
        config = FConfig.query_one(server_name=arg['server_name'])
        if config:
            return Msg.success(**marshal(base, config))


class ConfigInfo(Resource):
    def get(self):
        return Msg.success(server_name=SERVER_NAME)


class SSr(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('users', required=True, type=dict, action='append')

    @auth_token()
    @admin_authority
    def get(self):
        ms = MSsr()
        da = ms.get_user_list()
        status = ms.get_server_status()
        return Msg.success(users=da, status=status)

    @auth_token()
    @admin_authority
    def post(self):
        arg = self.parse.parse_args()
        status = MSsr().update_user_list(arg.get('users'))
        if status[0] == 1:
            return Msg.success(status[1])
        return Msg.failed(status[1])


class SrSS(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('cmd', required=True, type=str)

    get_parse = reqparse.RequestParser()
    get_parse.add_argument('lines', type=int)

    @auth_token()
    @admin_authority
    def get(self):
        arg = self.get_parse.parse_args()
        da = MSsr().get_server_log(arg.get('lines'))
        return Msg.success(lines=da[0], logs=da[1])

    @auth_token()
    @admin_authority
    def post(self):
        arg = self.parse.parse_args()

        cmd = arg['cmd']
        msg = ''
        if cmd == 'restart':
            msg = MSsr().restart_server()
        elif cmd == 'stop':
            msg = MSsr().stop_server()
        elif cmd == 'status':
            status = MSsr().get_server_status()
            return Msg.success(stutus=status)
        return Msg.success(msg)


class MSyncTasks(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('task_name', required=True, type=str)
    parse.add_argument('status', required=True, type=str)

    @auth_token()
    @admin_authority
    def get(self):
        arg = self.parse.parse_args()
        task_name = arg['task_name']
        status = arg['status']

        task = SysTasks.query_one(task_name=task_name)
        if task:
            if status == 'start':
                if task.status == 'stop':
                    task.update(status='start')
                    ta = all_tasks.get(task_name)
                    print(ta)
                    executor.submit(ta)

                    return Msg.success('任务已启动')
                return Msg.failed_dict(3001)
            elif status == 'stop':
                task.update(status='stop')
                return Msg.success()
        return Msg.failed_dict(3000)


class RecMusic(Resource):
    def get(self):
        with open(os.path.join(UPLOAD_PATH, 'rec_1.mp3'), 'rb') as f:
            data = f.read()
        resp = make_response(data)
        resp.headers["Content-Disposition"] = f"attachment; filename*=utf-8''recommend_music.mp3"
        resp.headers["Content-Type"] = f"application/octet-stream; charset=utf-8"
        return resp


class HomeNotice(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('notice_type', type=str, choices=('home', 'topic_comment', 'login'), required=True)

    def get(self):
        arg = self.parse.parse_args()
        notice = Notice.query_one(enable=1, **arg)

        value = {
            'msg': '',
            'text': '',
            'url': '',
            'show_close': True,
            'show': False,
            'id': None
        }
        if notice:
            m_val = marshal(value, notice)
            return Msg.success(notice=m_val)
        return Msg.success()


api.add_resource(CrudConfig, '/config', endpoint='config')
api.add_resource(ConfigInfo, '/config/info', endpoint='config_info')
api.add_resource(SSr, '/config/ss', endpoint='ss')
api.add_resource(SrSS, '/config/ss/f_manage', endpoint='ss_m')
api.add_resource(MSyncTasks, '/config/tasks', endpoint='tasks')
api.add_resource(RecMusic, '/config/recommend/music', endpoint='rec_music')
api.add_resource(HomeNotice, '/config/notice')
